package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.mapper.UserInfoMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.entity.Message;
import com.example.demo.entity.User;
import com.example.demo.entity.UserInfo;
import com.example.demo.util.IPUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Controller
public class RegisterController {

    @Autowired
    private UserMapper um;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @RequestMapping("/registers")
    public void regist(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String nation=request.getParameter("nation");
        String email=request.getParameter("email");
        String inputcode=request.getParameter("code");
        String code=(String)request.getSession().getAttribute("emailCode");
        List<User> list =new ArrayList<User>();
        list=um.findAlll();
        boolean isEmailExist=list.stream().anyMatch(user -> Objects.equals(user.getEmail(), email));
    if(code.equals(inputcode)&&!isEmailExist){
            User u=um.selectLast();
            BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
            String passwords=encoder.encode(password);
            User user=new User(u.getId()+1,username,passwords, IPUtil.getClientIpAddress(request), email,3,1,null);
            UserInfo userinfo=new UserInfo(user.getName(),nation,user.getEmail(),18,1);
            int n=um.register(user);
            int num=userInfoMapper.registers(userinfo);
            if(n>0&&num>0) {response.getWriter().write(JSONObject.toJSONString(Message.success("Success register")));}
            else {response.getWriter().write(JSONObject.toJSONString(Message.failure(400,"Register is failed")));}
        }else response.getWriter().write(JSONObject.toJSONString(Message.failure(400,"code is error or email is exist")));
    }
}
